import React, { Component } from 'react';
import { Input, Table, Pagination,Switch,Button,Feedback,Grid,Dialog } from '@icedesign/base';
import SysDynamicIcon from '../../../../../../components/SysDynamicIcon';
import API from '../../../../../../tools/API';
import IceContainer from '@icedesign/container';
import AddUser from './AddUser/AddUser';
import EditUser from './EditUser/EditUser';
import QueryUser from './QueryUser/QueryUser';
import ErpAuth from '../../../../../ErpBase/ErpAuth/ErpAuth';

const {Row, Col} = Grid;
/**
*  用户列表查询
*/
export default class TableFilter extends Component {
  static displayName = 'TableFilter';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      current: 1,
      total:1,
      dataSource:[],
      rowSelection: {
        onChange: this.onRowChange.bind(this),
        selectedRowKeys: [],
        getProps: record => {
          return {
            disabled: record.id === "1"
          };
        }
      },
      query:{},
      isLoading:true,
      roleSelectData:[]
    };
    this.getUserList = this.getUserList.bind(this);
    this.updateQuery = this.updateQuery.bind(this);
  }

  //更新查询
  updateQuery = (json)=>{
    this.state.query = json;
    this.setState(this.state);
  }


  //行选中
  onRowChange(ids, records) {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = ids;
    this.setState({ rowSelection });
  }

  //用户删除
  deleteUser = ()=>{
    //用户列表查询
    let {selectedRowKeys} = this.state.rowSelection;
    if (selectedRowKeys.length == 0) {
      Feedback.toast.prompt("请选择需要删除的用户");
    } else {
      let dialog = Dialog.confirm({
        content: "确定要删除吗？",
        locale: {
          ok: "确认",
          cancel: "取消"
        },
        onOk: () => {
          return new Promise(resolve => {
            API.delUser({ids:this.state.rowSelection.selectedRowKeys}).then((res) => {
              Feedback.toast.success("删除成功");
              this.getUserList();
              dialog.hide();
            });
          });
        }
      });
    }
  }

  getUserList = (json)=>{
    //刷新列表
    API.getUserListData(this.state.query).then((res) => {
      this.state.current = res.result.pageNumber;
      this.state.total = res.result.totalRow;
      this.state.dataSource = res.result.list;
      this.state.isLoading = false;
      this.setState(this.state);
    });
  }

  //初始化
  componentWillMount(){
    //用户列表查询
    this.getUserList();
    this.setState({roleSelectData:API.getRoleSelectData().result});
  }

  handlePaginationChange = (current) => {
    this.state.query["pageNum"] = current;
    this.setState(this.state);
    this.getUserList();
  };

  onChange = (value) =>{
    //console.log( value );
  };

  renderHead = (value,index,record,context)=>{
    return (
      <div>
        <img src={record.head_img}
          width="50px"
          height="50px"
          style={{
            borderRadius:50
          }}></img>
      </div>
    )
  }

  renderName = (value,index,record,context)=>{
    return (
      <div>
        <div style={styles.renderName}>{record.nick_name}
          <SysDynamicIcon style={record.sex==1?styles.renderMan:record.sex==2?styles.renderWoman:styles.xingbie}
            type={record.sex==1?"nan":record.sex==2?"nv":"xingbie"} />
        </div>
        <div style={styles.renderEmail}>{record.email}</div>
      </div>
    )
  }

  renderSwitch = (value,index,record,context)=>{
    return <Switch style={{color:'#2077FF'}} defaultChecked={record.login_flag == 0?true:false} onChange={this.switchChange.bind(this,record)} size="small" />
  }

  resetPwd = (id)=>{
    API.resetPwd({"id":id}).then((res) => {
      Feedback.toast.success("密码重置成功，默认密码为："+res.result.defaultPwd);
    });
  }

  switchChange = (record,value)=>{
    record.login_flag = value?0:1
    API.updateUserInfo(record);
  }

  renderOper = (value,index,record,context) => {
    return (
      <div>
        <EditUser user={record} style={styles.link} getUserList={this.getUserList} roleSelectData={this.state.roleSelectData} />
        <a style={styles.link} onClick={this.resetPwd.bind(this,record.id)}>重置密码</a>
      </div>
    );
  };

  render() {
    const dataSource = this.state.dataSource;
    const { current } = this.state;
    const { total } = this.state;

    return (
      <div>
        {/* <IceContainer style={styles.searchContent}>

        </IceContainer> */}
        <IceContainer title="用户列表" loading={this.state.isLoading}>
            <QueryUser updateQuery={this.updateQuery} getUserList={this.getUserList} />
            <div style={styles.container}>
              <Row justify='center'>
                <Col span='12'>
                  <ErpAuth authKey="user_add">
                    <AddUser getUserList={this.getUserList} roleSelectData={this.state.roleSelectData} />
                  </ErpAuth>
                </Col>
                <Col span='12' style={{textAlign:'right'}}>
                  <Button onClick={this.deleteUser}>删除</Button>
                  <Button style={{margin:'0 5px'}} onClick={()=>window.location.href=API.url().exportExcel4User}>下载</Button>
                </Col>
              </Row>
            </div>
            <Table dataSource={dataSource} hasBorder={false}  rowSelection={this.state.rowSelection}>
              <Table.Column align={"center"} title="头像" cell={this.renderHead.bind(this)} width={100} />
              <Table.Column align={"center"} title="姓名" cell={this.renderName.bind(this)} width={130} />
              <Table.Column align={"center"} title="用户名" dataIndex="user_name" width={100} />
              <Table.Column align={"center"} title="手机号" dataIndex="phone" width={120} />
              <Table.Column align={"center"} title="创建时间" dataIndex="create_date" width={100} />
              <Table.Column align={"center"} title="启用/停用" cell={this.renderSwitch.bind(this)} width={100} />
              <Table.Column align={"center"} title="操作" cell={this.renderOper} width={140} />
            </Table>
            <Pagination
              style={styles.pagination}
              current={current}
              onChange={this.handlePaginationChange}
              total={total}
            />
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  searchContent:{
    marginBottom:10
  },
  container: {
    marginBottom:10
  },
  tableHead: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: '20px',
  },
  link: {
    margin: '0 5px',
    color: 'rgba(49, 128, 253, 0.65)',
    cursor: 'pointer',
    textDecoration: 'none',
  },
  separator: {
    margin: '0 8px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
  pagination: {
    marginTop: '20px',
    textAlign: 'right',
  },
  renderName:{
    fontSize: 15,
    fontWeight: 'bold',
    margin: '5px 0',
    marginTop:-5
  },
  renderEmail:{
    fontSize:13,
    color:'#999999'
  },
  renderMan:{
    fontSize: 12,
    lineHeight: 1,
    marginLeft: 8,
    color: '#2eca9c'
  },
  renderWoman:{
    fontSize: 12,
    lineHeight: 1,
    marginLeft: 8,
    color: '#fa7070'
  },
  xingbie:{
    fontSize: 15,
    lineHeight: 1,
    marginLeft: 8,
    color: '#ffa000'
  }
};
